require('../css/login.less')

document.ready(function () {

    //获取dom节点
    let registerBtn = document.querySelector('#registerBtn'); //注册按钮
    let phoneNum = document.querySelector('#phoneNum'); //电话
    let password = document.querySelector('#password'); //密码
    let loginBtn = document.querySelector('#loginBtn'); //按钮
    let hint = document.querySelector('#hint'); //提示语

    //跳转到登录
    registerBtn.addEventListener('click', function () {
        location.href = './register.html'
    })

    //如果有数据就渲染到input框，没有就

    //登录
    loginBtn.addEventListener('click', function () {
        let phoneNumVal = phoneNum.value; //手机值
        let passwordVal = password.value; //密码值

        //手机
        if (phoneNumVal === '') {
            hint.textContent = '手机号不能为空！'
            return
        } else if (!window.utils.isPhoneNumber(phoneNumVal)) {
            hint.textContent = '手机号格式错误！'
            return;
        }
        //密码
        if (passwordVal === '') {
            hint.textContent = '密码不能为空！'
            return
        } else if (!window.utils.isPassword(passwordVal)) {
            hint.textContent = '密码格式错误！'
            return;
        }

        //发送登录请求
        window.$http.post('/users/login', {
                account: phoneNumVal,
                password: passwordVal,
            },
            function (res) {
                if (res.status === 0) {
                    console.log(res);
                    let obj = {
                        userId: res.data.user.userId,
                        account: phoneNumVal,
                        password: passwordVal,
                        nickname: res.data.user.nickname,
                        gender: res.data.user.gender,
                        birthday: res.data.user.birthday,
                        imgurl: res.data.user.imgurl,
                        address: res.data.user.address,
                        sign: res.data.user.sign,
                        describe: res.data.user.describe,
                        token: res.data.user.token
                    }
                    console.log(obj);
                    localStorage.setItem('user', JSON.stringify(obj))
                    window.utils.toast('tick', '登录成功');
                    window.setTimeout(function () {
                        location.href = './index.html'
                    }, 2000)
                } else {
                    // 登录失败
                    console.log(res.msg);
                    hint.textContent = res.msg;
                    window.utils.toast('fork', res.msg);
                }
            }
        )
    })

})